<?php
/**
 * Created by PhpStorm.
 * User: gesangdianzi
 * Date: 2018/4/15
 * Time: 15:35
 */

namespace common\Com;


use common\models\Article;
use common\models\ArticleTxt;

class Caiji
{

    public $match ;
    public function __construct()
    {
        $this->match = new CurlMatch();
    }

    /**
     * 采集文章图片，并保存文章
     */
    public function saveArticle($items){
        if(empty($items)){
            return false;
        }
        $time = time();
        $model = new  Article();
        $txt = new ArticleTxt();
        foreach ($items as $k=>$item){
            //记录不存在，插入记录
            if(!Article::find()->where(['title'=>$item['t']])->exists()){
                $_model = clone $model;
                $_model->cat = 2;//2行业资讯，3网站建设，4app制作，5小程序开发，6网站优化
                $_model->title = $item['t'];
                $_model->keyword = $item['k'];
                $_model->info = $item['d'];
                $_model->created_at = $time;
                $_model->updated_at = $time;
                $_model->online = 1;
                if($_model->save()){
                    $_txt = clone $txt;
                    $this->saveTxt($_model->id,$_txt,$item['c']);
                }
            }

        }
    }

    public function saveTxt($id,$txt,$content){
        $content = strip_tags($content,"<b><img><a><style><p><br>");
        $txt->id =$id;
        $txt->text = $content;
        if($txt->save()){
            preg_match_all('/'.preg_quote('<img').'[^\>]*src=[\'\"]([^\>\'\"]*)[\'\"][^\>]*'.preg_quote('/>','/').'/',$content,$out);
            if(isset($out[1]) && !empty($out[1])){
                foreach ($out[1] as $i => $url){
                    $pic = $this->match->getPic($this->match->_host.$url);
                    if(!empty($pic) && !is_bool($pic)){
                        $dir = \Yii::getAlias("@frontend/web/upload/caiji/");
                        $name = date("Ym").md5($url).'_'.$i.".jpg";
                        $filename = $dir.$name;
                        $fp = @fopen($filename,"a"); //将文件绑定到流

                        fwrite($fp,$pic); //写入文件
                        $path = "/upload/caiji/".$name;
                        $content = preg_replace('/'.preg_quote($url,'/').'/',$path,$content);
                    }
                }
            }
            $txt->text = $content;
            $txt->save();
        }
    }

    /**
     * @throws \yii\base\Exception 采集方为网络
     */
    public function getSzfangwei(){
        $match = $this->match;
        $list = $match->alist('http://www.szfangwei.cn/news/','<div class="news_list"></div>');

        foreach ($list as $k =>$vo){
            $list[$k] =  $match->fixUrl($vo);
        }
        $contentList = [];
        $contentKey = '<div class="news_box fl"></div>';
        foreach($list as $key => $value){
            $tmp['c'] = $match->content($value , $contentKey);
            $tmp['c'] = preg_replace('/方维网络/','昂追网络',$tmp['c']);
            $tmp['c'] = preg_replace('/作者[^\<\>]*/','',$tmp['c']);
            $match->_data = preg_replace('/方维网络/','昂追网络',$match->_data);

            if(preg_match('/'.preg_quote('<meta name="keywords" content="').'([^\>]*)'.preg_quote('" />','/').'/',$match->_data,$out)){
                //<meta name="keywords" content="深圳网站定制,网站定制报价" />
                $tmp['k'] = $out[1];
            }else{
                $tmp['k'] = "";
            }
            if(preg_match('/'.preg_quote('<meta name="description" content=').'"([^\>]*)"\s*'.preg_quote('/>','/').'/',$match->_data,$out)){
                //<meta name="description" content="   深圳做网站需要报价一般是针对定制建站，模板建站就无所谓报价了，因为模板建站实施不需要设计师和开发工程师，都是固定价格。深圳作为国内定制建站的几大热门城市..."  />
                $tmp['d'] = $out[1];
            }else{
                $tmp['d'] = "";
            }
            if(!empty($tmp)){
                $contentList[] = $tmp;
            }
        }
        $items = [];
        if(!empty($contentList)){
            foreach ($contentList as $item){
                $title = $match->match('<h1></h1>',$item['c'],'data');
                $detail = $match->match('<div class="editor" id="editor"></div>',$item['c'],'content');
                $items[] = ['t'=>$title,'c'=>$detail,'k'=>$item['k'],'d'=>$item['d']];
            }
        }
        $this->saveArticle($items);
    }

    /**
     * 采集飞沐网
     */
    public function getFeimu(){
        //https://www.fimvisual.com/news/view/
//
//        $match = $this->match;
//        $list = $match->alist('https://www.fimvisual.com/news/view/','<section class="l-news-index"></section>');
//        $list = array_unique($list);
//        foreach ($list as $k =>$vo){
//            if($k<=4){
//                unset($list[$k]);
//            }
//            if(preg_match('/page/',$vo)){
//                unset($list[$k]);
//            }
//        }
//
//        $contentList = [];
//        $contentKey = '<article class="post__content"></article>';
//        foreach($list as $key => $value){
//            $tmp['c'] = $match->content($value , $contentKey);
//            if(preg_match('/'.preg_quote('<meta name="keywords" content="').'([^\>]*)'.preg_quote('" />','/').'/',$match->_data,$out)){
//                //<meta name="keywords" content="深圳网站定制,网站定制报价" />
//                $tmp['k'] = $out[1];
//            }else{
//                $tmp['k'] = "";
//            }
//            if(preg_match('/'.preg_quote('<meta name="description" content=').'"([^\>]*)"\s*'.preg_quote('/>','/').'/',$match->_data,$out)){
//                //<meta name="description" content="   深圳做网站需要报价一般是针对定制建站，模板建站就无所谓报价了，因为模板建站实施不需要设计师和开发工程师，都是固定价格。深圳作为国内定制建站的几大热门城市..."  />
//                $tmp['d'] = $out[1];
//            }else{
//                $tmp['d'] = "";
//            }
//            if(!empty($tmp)){
//                $contentList[] = $tmp;
//            }
//        }
//        var_dump($contentList);exit();
//        $items = [];
//        if(!empty($contentList)){
//            foreach ($contentList as $item){
//                $title = $match->match('<h1></h1>',$item['c'],'data');
//                $detail = $match->match('<div class="editor" id="editor"></div>',$item['c'],'content');
//                $items[] = ['t'=>$title,'c'=>$detail,'k'=>$item['k'],'d'=>$item['d']];
//            }
//        }
//        $this->saveArticle($items);
    }
}